<template>
  <div class="register-container">
    <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="0" class="register-form">
      <h3 class="title">注册</h3>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="registerForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item prop="confirm">
        <el-input type="password" v-model="registerForm.confirm" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>export default {
  data() {
    return {
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirm: ''
      },
      registerRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, message: '密码至少为6位', trigger: 'blur' }],
        confirm: [{ required: true, message: '请再次输入密码', trigger: 'blur' }, { validator: this.checkPass, trigger: 'blur' }]
      }
    };
  },
  methods: {
    checkPass(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致!'));
      } else {
        callback();
      }
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          // 发送注册请求
          this.$http.post('/api/register', this.registerForm).then(response => {
            // 注册成功后的处理
          }).catch(error => {
            // 处理错误
          });
        } else {
          console.log('注册失败，请检查输入信息');
        }
      });
    }
  }
};
</script>

<style scoped>.register-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}
.title {
  text-align: center;
  margin-bottom: 20px;
}
.register-form {
  width: 300px;
}
</style>
